import axios from 'axios'
import { getToken, removeToken } from '@/utils/auth'
import { ElNotification } from 'element-plus'

const axiosInstance = axios.create(
    {
        // 5s
        timeout: 5000,
        baseURL: '/api'
    }
)
axiosInstance.interceptors.request.use(
    config => {

        // request 拦截，在头部添加tokenName/Value
        const { tokenValue, tokenName} = getToken()
        
        if (tokenName && tokenValue) {
            config.headers[tokenName] = tokenValue
        }
        // 重复提交的处理？？？？
        return config
    },
    error => {
        console.log('requesr interceptors error:',error)
        Promise.reject(error)
    }

);
// 接收后拦截
axiosInstance.interceptors.response.use(
    res => {
        // console.log(response)
        // 二进制数据则直接返回
        if (res.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
            return res.data
        }
        // console.log('response interceptors:', res)

        if (res.status === 200) {
  
            if (res.data.code === 200) {
                return res.data
            }

            console.log('@@@@@###sError: ',res.data.code)
            if (res.data.code === 401) {
                // 后端返回token错误
                removeToken()
            }
            ElNotification({ title:'错误',message: res.data.msg, type: 'error' })
            return res.data
        }else{
            return Promise.reject(res.statusText)
        }
      
        
    },
    error => {
        console.log('Response Error:' + error)
        let { message } = error;
        // 前端 硬错误
        if (message == "Network Error") {
            message = "后端接口连接异常";
        } else if (message.includes("timeout")) {
            message = "系统接口请求超时";
        } else if (message.includes("Request failed with status code")) {
            message = "系统接口" + message.substr(message.length - 3) + "异常";
        }
        ElNotification({ message: message, type: 'error', duration: 5 * 1000 })
        return Promise.reject(error)
    }
)
export default axiosInstance

